package com.mmtech.controller;

import com.google.common.collect.Maps;
import com.mmtech.edb.data.config.DataSendConfig;
import com.mmtech.edb.data.handler.DataHandler;
import com.mmtech.edb.data.util.PlaceholderUtil;
import org.apache.commons.lang3.StringUtils;
import org.joda.time.DateTime;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Controller;
import org.springframework.ui.ModelMap;
import org.springframework.web.bind.annotation.RequestMapping;

import java.util.Map;

/**
 * 推送数据
 *
 * @author wuchong
 * @since 2019-07-16 17:20
 **/
@Controller
public class DataSendController {

    private final DataHandler dataHandler;

    private final DataSendConfig dataSendConfig;

    @Autowired
    public DataSendController(DataHandler dataHandler, DataSendConfig dataSendConfig) {
        this.dataHandler = dataHandler;
        this.dataSendConfig = dataSendConfig;
    }

    @RequestMapping("/send")
    public String send(ModelMap map, String startDate, String endDate) throws Exception {

        String yesterday = DateTime.now().minusDays(1).toString("yyyy-MM-dd");
        startDate = StringUtils.defaultIfEmpty(startDate, yesterday);
        endDate = StringUtils.defaultIfEmpty(endDate, yesterday);
        dataSendConfig.setStartDate(startDate);
        dataSendConfig.setEndDate(endDate);

        dataHandler.process();

        String date = dataHandler.assembleDate(startDate, endDate);
        Map<String, String> params = Maps.newHashMap();
        params.put("date", date);

        String subject = PlaceholderUtil.replace(dataSendConfig.getSubject(), params, "{", "}");
        map.put("message", "主题为" + subject + "的邮件发送成功");

        return "hello";
    }
}
